import React,{Component} from 'react';
import {
    StyleSheet,
    View,
    ScrollView,
    Text,
    Modal,
    StatusBar,
    Image,
    TouchableWithoutFeedback,
    Animated,
    Easing,
} from 'react-native';
import request from '../request/request';
import Header from './header/Header';
import ScrollableTabView, {DefaultTabBar} from 'react-native-scrollable-tab-view';
import ImagePicker from 'react-native-image-picker'
export default class UserInfo extends Component{
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
        	userImage: 'http://h.hiphotos.baidu.com/zhidao/pic/item/3bf33a87e950352ae1dc27695243fbf2b2118b15.jpg',
            // 控制tab所在的页数
            page: 0,
            // 性别
            sex: '男',
            // 年龄段
            age: '18-25',
            // 暂时存放用户所选择的区域
            addressTep: ['','',''],
            // 显示用户所选择的区域
            addressInfo: '广东 深圳 宝安',
            // 地址id
            addressId: '',
            // 弹窗初始数据
            currentPosition: 350,//缩放标志位，记录当前value
            position: new Animated.Value(350), //设置初始值
            // 弹窗的显示与隐藏
            mask: false,
            // 省市区数据
            provinceData: [],
            cityData: [],
            areaData: [],

            showModal: false,
            showModalAge: false,
        };
    }
    componentWillMount(){
        let that = this;
        fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id=100000',
            {
                method: 'GET',
            }
        )
        .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
        .then((responseData) => {   // 获取到的数据处理
            for(let i=0;i<responseData.result.length;i++){
                responseData.result[i].isChoose = false;
            }
            that.setState({
                provinceData: responseData.result
            });
            console.log(responseData.result)
        })
        .catch((error) => {     // 错误处理
            console.log(666)
        })
        .done();
    }

    getCityData(data, index){
        let that = this;
        this.state.addressTep[0] = '';
        for(let i=0;i<this.state.provinceData.length;i++){
            if(i==index){
                this.state.provinceData[i].isChoose = true;
                
                this.state.addressTep[0] = this.state.provinceData[i].name;
            }else {
                this.state.provinceData[i].isChoose = false;
            }
        }
        this.setState({
            page: 1,
            addressTep: this.state.addressTep,
            provinceData: this.state.provinceData,
            cityData: [],
            areaData: [],
        },function(){
            fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id='+data,
                {
                    method: 'GET',
                }
            )
            .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
            .then((responseData) => {   // 获取到的数据处理
                for(let i=0;i<responseData.result.length;i++){
                    responseData.result[i].isChoose = false;
                }
                that.setState({
                    cityData: responseData.result
                });
                console.log(responseData.result)
            })
            .catch((error) => {     // 错误处理
                console.log(666)
            })
            .done();
        });
    }

    getAreaData(data, index){
        let that = this;
        this.state.addressTep[1] = '';
        for(let i=0;i<this.state.cityData.length;i++){
            if(i==index){
                this.state.cityData[i].isChoose = true;
                this.state.addressTep[1] = this.state.cityData[i].name;
            }else {
                this.state.cityData[i].isChoose = false;
            }
        }
        this.setState({
            page: 2,
            addressTep: this.state.addressTep,
            cityData: this.state.cityData,
            areaData: [],
        },function(){
            fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id='+data,
                {
                    method: 'GET',
                }
            )
            .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
            .then((responseData) => {   // 获取到的数据处理
                for(let i=0;i<responseData.result.length;i++){
                    responseData.result[i].isChoose = false;
                }
                that.setState({
                    areaData: responseData.result
                });
                // console.log(responseData)
            })
            .catch((error) => {     // 错误处理
                console.log(666)
            })
            .done();
        });
    }

    chooseFinish(data, index){
        let that = this;
        this.state.addressTep[2] = '';
        for(let i=0;i<this.state.areaData.length;i++){
            if(i==index){
                this.state.areaData[i].isChoose = true;
                this.state.addressTep[2] = this.state.areaData[i].name;
            }else {
                this.state.areaData[i].isChoose = false;
            }
        }
        this.state.addressInfo = this.state.addressTep.join(' ');
        this.chooseAddress();
        this.setState({
            addressId: data,
            addressTep: this.state.addressTep,
            addressInfo: this.state.addressInfo,
        })
    }

    chooseAddress(){
        let that = this;
        this.setState({
            mask: !this.state.mask
        },function () {
            that.state.currentPosition = that.state.currentPosition==350?0:350;
            Animated.spring(
                that.state.position,
                {
                    toValue: that.state.currentPosition,
                    easing: Easing.linear,
                    speed: 8,
                    bounciness: 5,
                    useNativeDriver: true
                }
            ).start()
        });
        
    }

    chooseImage(){
    	let that = this;
    	const photoOptions = {
		    title:'请选择',
		    quality: 0.8,
		    cancelButtonTitle:'取消',
		    takePhotoButtonTitle:'拍照',
		    chooseFromLibraryButtonTitle:'选择相册',
		    allowsEditing: true,
		    noData: false,
		    storageOptions: {
		        skipBackup: true,
		        path: 'images'
		    }
		};

		ImagePicker.showImagePicker(photoOptions, (response) => {
            console.log('Response = ', response);
            if (response.didCancel) {
            	// 用户取消选择
                console.log('User cancelled image picker');
            }
            else if (response.error) {
            	// 发生错误
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                // let source = { uri: response.uri };
                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };
                this.setState({
                    userImage: response.uri
                });
            }
        });
    }

    // modal的android返回键回调
    onRequestClose(){
    	this.setState({
    		showModal: false,
    		showModalAge: false
    	});
    }

    render(){
        const { params } = this.props.navigation.state;
        const {navigate,goBack,state} = this.props.navigation;
        let barHeight = StatusBar.currentHeight;
        return (
            <View style={{
                flex: 1,
                // paddingTop: barHeight, 
                backgroundColor: '#eaeaea'
            }}>
                <Header isShowBack={true} title='个人信息' goBack={goBack} />

				<View style={styles.setBox}>
					<TouchableWithoutFeedback onPress={()=>this.chooseImage()}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>头像</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Image style={{width: 45, height: 45, borderRadius: 50}} source={{uri: this.state.userImage}}/>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>
                <View style={styles.setBox}>
                	<TouchableWithoutFeedback onPress={()=>navigate('ChangeNick', {oldNick: '林帅帅'})}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>昵称</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Text style={{fontSize: 13, color: '#000'}}>林帅帅</Text>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>
                <View style={styles.setBox}>
                	<TouchableWithoutFeedback onPress={()=>navigate('ChangeMobile')}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>电话</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Text style={{fontSize: 13, color: '#000'}}>1388888888</Text>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>
                <View style={styles.setBox}>
                	<TouchableWithoutFeedback onPress={()=>this.setState({showModal: true})}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>性别</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Text style={{fontSize: 13, color: '#000'}}>{this.state.sex}</Text>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>
                <View style={styles.setBox}>
                	<TouchableWithoutFeedback onPress={()=>this.setState({showModalAge: true})}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>年龄段</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Text style={{fontSize: 13, color: '#000'}}>{this.state.age}</Text>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>
                <View style={styles.setBox}>
	                <TouchableWithoutFeedback onPress={()=>this.chooseAddress()}>
	                    <View style={styles.setBoxItem}>
	                        <Text style={styles.setBoxItemText}>地区</Text>
	                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
	                            <Text style={{fontSize: 13, color: '#000'}}>{this.state.addressInfo}</Text>
	                            <Image style={[styles.setBoxItemImage, {marginLeft: 8}]} source={require('../images/rightGo.png')}/>
	                        </View>
	                    </View>
                    </TouchableWithoutFeedback>
                </View>

				{/* 性别选择弹窗 */}
                <Modal
	                animationType='fade'           // 淡入淡出
	                transparent={true}              // 透明
	                visible={this.state.showModal}    // 根据isModal决定是否显示
	                onRequestClose={this.onRequestClose.bind(this)}  // android必须实现
	            >	
	            	<TouchableWithoutFeedback onPress={()=>this.setState({showModal: false})}>
	                	<View style={{position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)'}}></View>
	                </TouchableWithoutFeedback>
	                <View style={[styles.child, {marginTop: -75-(barHeight/2)}]}>
	                	<View style={{flex: 1, padding: 15, borderBottomWidth: 1, borderColor: '#ddd'}}>
	                		<Text style={styles.childText}>选择年龄段</Text>
	                	</View>
	                	<TouchableWithoutFeedback onPress={()=>this.setState({showModal: false, sex: '男'})}>
		                	<View style={{flex: 1, padding: 15, borderBottomWidth: 1, borderColor: '#ddd'}}>
		                		<Text style={styles.childText}>男</Text>
		                	</View>
	                	</TouchableWithoutFeedback>
                		<TouchableWithoutFeedback onPress={()=>this.setState({showModal: false, sex: '女'})}>
		                	<View style={{flex: 1, padding: 15}}>
		                		<Text style={styles.childText}>女</Text>
		                	</View>
		                </TouchableWithoutFeedback>
                    </View>
	            </Modal>

	        	{/* 年龄选择弹窗 */}
                <Modal
	                animationType='fade'           // 淡入淡出
	                transparent={true}              // 透明
	                visible={this.state.showModalAge}    // 根据isModal决定是否显示
	                onRequestClose={this.onRequestClose.bind(this)}  // android必须实现
	            >	
	            	<TouchableWithoutFeedback onPress={()=>this.setState({showModalAge: false})}>
	                	<View style={{position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)'}}></View>
	                </TouchableWithoutFeedback>
	                <View style={[styles.child, {marginTop: -100-(barHeight/2), height: 200}]}>
	                	<View style={{flex: 1, padding: 15, borderBottomWidth: 1, borderColor: '#ddd'}}>
	                		<Text style={styles.childText}>选择性别</Text>
	                	</View>
	                	<TouchableWithoutFeedback onPress={()=>this.setState({showModalAge: false, age: '18-25'})}>
		                	<View style={{flex: 1, padding: 15, borderBottomWidth: 1, borderColor: '#ddd'}}>
		                		<Text style={styles.childText}>18-25</Text>
		                	</View>
	                	</TouchableWithoutFeedback>
                		<TouchableWithoutFeedback onPress={()=>this.setState({showModalAge: false, age: '25-35'})}>
		                	<View style={{flex: 1, padding: 15, borderBottomWidth: 1, borderColor: '#ddd'}}>
		                		<Text style={styles.childText}>25-35</Text>
		                	</View>
		                </TouchableWithoutFeedback>
		                <TouchableWithoutFeedback onPress={()=>this.setState({showModalAge: false, age: '35以上'})}>
		                	<View style={{flex: 1, padding: 15}}>
		                		<Text style={styles.childText}>35以上</Text>
		                	</View>
		                </TouchableWithoutFeedback>
                    </View>
	            </Modal>

				{/* 省市联动弹窗 */}
                {
                    this.state.mask?
                    <TouchableWithoutFeedback onPress={()=>this.chooseAddress()}>
                        <View style={{position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)', zIndex: 100}}></View>
                    </TouchableWithoutFeedback>
                    :
                    null
                }
                
                <Animated.View style={{height: '50%', position: 'absolute', left: 0, right: 0, bottom: 0, transform: [{translateY:this.state.position}], backgroundColor: '#fff', zIndex: 1000}}>
                    <View style={{height: 36, justifyContent: 'center', alignItems: 'center'}}>
                        <Text>配送至</Text>
                    </View>
                    <ScrollableTabView
                        // 默认选项卡栏下划线的样式
                        tabBarUnderlineStyle={{height: 2, backgroundColor: '#0000ff'}}
                        // 默认标签栏背景的颜色，默认为white
                        tabBarBackgroundColor={'white'}
                        // 选中时默认标签栏文本的颜色，默认为navy
                        tabBarActiveTextColor={'#0000ff'}
                        // 不选中时默认标签栏文本的颜色，默认为black
                        tabBarInactiveTextColor={'black'}
                        // 标签栏文本的其他样式
                        tabBarTextStyle={{fontSize: 14, fontWeight: 'normal'}}
                        // 最初选择的选项卡的索引，默认为0 ===第一个选项卡
                        initialPage={0}
                        // 动态设置当前显示的tab
                        page={this.state.page}
                        // TabBar组件
                        renderTabBar={() => <DefaultTabBar style={{height: 30}} />}
                        // 当选项卡更改时调用的函数。i：页面下标，ref：所选标签的引用
                        // onChangeTab={(obj)=>console.log(obj.i,obj.ref)}
                        // onChangeTab={this._tabChoose.bind(this)}
                        // 页面滑动时调用的函数。num：选项卡所处的位置
                        // onScroll={(num)=>console.log(num)}
                    >
                        <ScrollView
                            tabLabel='省级'
                        >
                            {
                                this.state.provinceData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.getCityData(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                        <ScrollView
                            tabLabel='市级'
                        >
                            {
                                this.state.cityData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.getAreaData(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                        <ScrollView
                            tabLabel='地区'
                        >
                            {
                                this.state.areaData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.chooseFinish(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                    </ScrollableTabView>
                </Animated.View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    setBox: {backgroundColor: '#fff', paddingLeft: 12},
    setBoxItem: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingTop: 12, paddingBottom: 12, paddingRight: 12, borderBottomWidth: 1, borderColor: '#e9e9e9' },
    setBoxItemText: {fontSize: 14, color: '#000'},
    setBoxItemImage: {width: 8,height: 16},
    cityBox: {paddingLeft: 10, paddingRight: 10, height: 34, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#ddd'},
    cityBoxText: {fontSize: 13, color: '#000'},

    container: {flex: 1, },
    child: {backgroundColor: '#fff', position: 'absolute', zIndex: 1000, left: '50%', top: '50%', marginLeft: -135, width: 270, height: 150, borderRadius: 12},
	childText: {fontSize: 14, color: '#000'},
})